package com.yisearch.search.autorunner;

/*
 * 环境初始化，检查es状态
 * 实现环境启动以后，自动运行。
 * @author yp
 * @date 2019/10/23
 * @param
 * @return
 */

import org.frameworkset.elasticsearch.boot.BBossESStarter;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.net.URL;

@Component
@Order(1)
public class EsEnvInitRunner implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(EsEnvInitRunner.class);


    @Autowired
    private BBossESStarter bBossESStarter;

    @Value("${spring.elasticsearch.bboss.elasticsearch.rest.hostNames}")
    private String esHostNames;


    @Override
    public void run(String... args) throws Exception {
        logger.info("=======开始检查es状态=======");
        //检查es状态
        chkStatus();
    }

    /**
     * 检查es状态
     */
    public void chkStatus() {
        ClientInterface client = bBossESStarter.getRestClient();
        try {
            URL targetUrl = new URL("http://" + esHostNames);
            HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setConnectTimeout(5000);
            if (httpConnection.getResponseCode() == 200) {
                logger.info("=====es状态正常=====");
            } else {
                httpConnection.disconnect();
                System.exit(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //es状态问题，直接停掉。
            System.exit(0);
        }
        logger.info("=========es状态检查完毕=======");

    }
}
